package com.bianmaba.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public final class HttpRequestUtil {
    public static final Logger LOG = LoggerFactory.getLogger(HttpRequestUtil.class);
    private RequestConfig requestConfig = RequestConfig.custom().build();

    private HttpRequestUtil() {
    }

    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     * @param params  参数
     */
    public static String sendHttpPost(String httpUrl, Map<String, String> params) {

        try {
            HttpPost httpRequest = createHttpRequest(httpUrl, params);
            return sendHttp(httpRequest, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送 post请求
     *
     * @param httpsUrl 地址
     * @param params   参数
     */
    public static String sendHttpsPost(String httpsUrl, Map<String, String> params) {


        HttpPost httpRequest = createHttpRequest(httpsUrl, params);
        return sendHttps(httpRequest, null, null);

    }

    private static HttpPost createHttpRequest(String httpUrl, Map<String, String> params) {
        try {
            HttpPost httpRequest = new HttpPost(httpUrl);// 创建httpPost
            // 创建参数队列
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
            }
            httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            return httpRequest;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送 get请求
     *
     * @param httpUrl
     */
    public static String sendHttpPost(String httpUrl, Map<String, String> params, List<File> files) {
        HttpPost httpPost = createHttpRequest(httpUrl, params, files);
        return sendHttp(httpPost, null, null);
    }

    public static String sendHttpsPost(String httpsUrl, Map<String, String> params, List<File> files) {
        HttpPost httpPost = createHttpRequest(httpsUrl, params, files);
        return sendHttps(httpPost, null, null);
    }

    private static HttpPost createHttpRequest(String url, Map<String, String> params, List<File> files) {
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        for (String key : params.keySet()) {
            multipartEntityBuilder.addPart(key, new StringBody(params.get(key), ContentType.TEXT_PLAIN));
        }
        for (File file : files) {
            FileBody fileBody = new FileBody(file);
            multipartEntityBuilder.addPart("files", fileBody);
        }
        HttpEntity entity = multipartEntityBuilder.build();
        httpPost.setEntity(entity);
        return httpPost;
    }


    /**
     * 发送 get请求
     *
     * @param httpUrl
     */
    public static String sendHttpGet(String httpUrl) {
        HttpGet httpRequest = new HttpGet(httpUrl);// 创建get请求
        return sendHttp(httpRequest, null, null);
    }

    /**
     * 发送 get请求Https
     *
     * @param httpsUrl
     */
    public static String sendHttpsGet(String httpsUrl) {
        HttpGet httpRequest = new HttpGet(httpsUrl);// 创建get请求
        return sendHttps(httpRequest, null, null);
    }

    public static String sendHttp(HttpRequestBase httpRequest, SSLConnectionSocketFactory sslsf, BasicCookieStore cookieStore) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseText = null;
        try {
            httpClient = createHttpClient(httpRequest.getURI().toString(), sslsf, cookieStore);
            if (httpClient != null) {
                // 执行请求
                response = httpClient.execute(httpRequest);
                HttpEntity entity = response.getEntity();
                responseText = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtils.close(response);
            StreamUtils.close(httpClient);
        }
        return responseText;
    }


    public static String sendHttps(HttpRequestBase httpRequest, SSLConnectionSocketFactory sslsf, BasicCookieStore cookieStore) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseText = null;
        try {
            httpClient = createHttpsClient(httpRequest.getURI().toString(), sslsf, cookieStore);
            if (httpClient != null) {
                // 执行请求
                response = httpClient.execute(httpRequest);
                HttpEntity entity = response.getEntity();
                responseText = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtils.close(response);
            StreamUtils.close(httpClient);
        }
        return responseText;
    }

    public static CloseableHttpClient createHttpClient(String url) {
        CloseableHttpClient client = createHttpClient(url, null, null);
        return client;
    }

    public static CloseableHttpClient createHttpClient(String url, SSLConnectionSocketFactory sslsf) {
        CloseableHttpClient client = createHttpClient(url, sslsf, null);
        return client;
    }

    public static CloseableHttpClient createHttpClient(String url, BasicCookieStore cookieStore) {
        CloseableHttpClient client = createHttpClient(url, null, cookieStore);
        return client;
    }

    public static CloseableHttpClient createHttpClient(String url, SSLConnectionSocketFactory sslsf, BasicCookieStore cookieStore) {
        CloseableHttpClient client = createClient(url, null, sslsf, cookieStore);
        return client;
    }

    public static CloseableHttpClient createHttpsClient(String url) {
        return createHttpsClient(url, null, null);
    }

    public static CloseableHttpClient createHttpsClient(String url, SSLConnectionSocketFactory sslsf) {
        return createHttpsClient(url, sslsf, null);
    }

    public static CloseableHttpClient createHttpsClient(String url, BasicCookieStore cookieStore) {
        return createHttpsClient(url, null, cookieStore);
    }

    public static CloseableHttpClient createHttpsClient(String url, SSLConnectionSocketFactory sslsf, BasicCookieStore cookieStore) {
        CloseableHttpClient client = null;
        try {
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(url));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            client = createClient(url, hostnameVerifier, sslsf, cookieStore);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return client;
    }

    public static CloseableHttpClient createClient(String url, DefaultHostnameVerifier hostnameVerifier, SSLConnectionSocketFactory sslsf, BasicCookieStore cookieStore) {
        HttpClientBuilder builder = HttpClients.custom();
        if (cookieStore != null) {
            builder.setDefaultCookieStore(cookieStore);
        }
        if (sslsf != null) {
            builder.setSSLSocketFactory(sslsf);
        }
        if (hostnameVerifier != null) {
            builder.setSSLHostnameVerifier(hostnameVerifier);
        }
        CloseableHttpClient client = builder.build();
        return client;
    }


    public static SSLConnectionSocketFactory createSSLConnectionSocketFactory(File keystore, String password) {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(keystore, password.toCharArray(),
                            new TrustSelfSignedStrategy())
                    .build();
            // Allow TLSv1 protocol only
            sslsf = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            return sslsf;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sslsf;
    }
}
